#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
/**
 * @brief 使用volitile来做实验，与x遥相呼应
 * 
 */
#define MAX_SIZE 500000000
typedef struct parameter
{
    int first;
    int last;
    int id;
}parameter_val;

volatile int result[2];
int* array = NULL;

/// @brief 两线程共用的函数,使用多线程实现5000个数相加
/// @param args 
/// @return 
void* myfunc(void* args)
{
    parameter_val* val = (parameter_val*)args;
    int sum = 0;
    int id = val->id;
    for(int i = val->first;i < val->last;i++)
    {
        result[id] = result[id]+array[i];
    }
    return NULL;
}

int main(int argc,char* argv[])
{
    pthread_t th1;
    pthread_t th2;
    array = malloc(sizeof(int)*MAX_SIZE);
    for(int i = 0; i< MAX_SIZE;i++)
    {
        array[i] = rand()%5;
    }
    int mid = MAX_SIZE/2;
    parameter_val val1 = {0,mid,0};
    parameter_val val2 = {mid,MAX_SIZE,1};
    result[0] = 0;
    result[1] = 0;

    pthread_create(&th1,NULL,myfunc,&val1);
    pthread_create(&th2,NULL,myfunc,&val2);

    pthread_join(th1,NULL);
    pthread_join(th2,NULL);

    printf("%d\n",result[0]);
    printf("%d\n",result[1]);
    printf("%d\n",result[0]+result[1]);
    return 0;

}